<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <el-form-item label="所属门店">
        <el-select v-model="listQuery.brandId" clearable size="small" class="filter-item" style="width: 200px;"
                   placeholder="请选择所属门店"
        >
          <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <el-row :gutter="30">
      <el-col :span="8">
        <el-card
          :body-style="{
            padding: '10px',
            background: '#B4EAFE',
            height: '160px',
          }"
          shadow="hover"
        >
          <div style="padding: 14px">
            <div class="itemTitle">
              账号总收入
            </div>
            <div class="itemNum">
              ￥
              <count-to
                :start-val="0"
                :end-val="totalAmount"
                :duration="3000"
                :decimals="2"
                class="card-panel-num"
              />
              元
            </div>
            <el-row :gutter="24">
              <el-col :span="24">
                <div class="itemTitle">
                  总成本
                </div>
                <div class="itemNum">
                  ￥
                  <count-to
                    :start-val="0"
                    :end-val="totalCostPrice"
                    :duration="3000"
                    :decimals="2"
                    class="card-panel-num"
                  />
                  元
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card
          :body-style="{
            padding: '10px',
            background: '#B4EAFE',
            height: '160px',
          }"
          shadow="hover"
        >
          <div style="padding: 14px">
            <div class="itemTitle">
              今日收入
            </div>
            <div class="itemNum">
              ￥
              <count-to
                :start-val="0"
                :end-val="currAmount"
                :duration="3000"
                :decimals="2"
                class="card-panel-num"
              />
              元
            </div>
            <div class="itemTitle">
              今日成本
            </div>
            <div class="itemNum">
              ￥
              <count-to
                :start-val="0"
                :end-val="curCostPrice"
                :duration="2000"
                class="card-panel-num"
              />
              元
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card
          :body-style="{
            padding: '10px',
            background: '#B4EAFE',
            height: '160px',
          }"
          shadow="hover"
        >
          <div style="padding: 14px">
            <div class="itemTitle">
              总佣金
            </div>
            <div class="itemNum">
              ￥
              <count-to
                :start-val="0"
                :end-val="totalSettlementAmount"
                :duration="3000"
                :decimals="2"
                class="card-panel-num"
              />
              元
            </div>
            <div class="itemTitle">
              可提现金额
            </div>
            <div class="itemNum">
              ￥
              <count-to
                :start-val="0"
                :end-val="curSettlementAmount"
                :duration="2000"
                class="card-panel-num"
              />
              元
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="选择日期">
          <el-date-picker
            v-model="listQuery.dateRange"
            :picker-options="pickerOptions"
            type="daterange"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >查找
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        align="center"
        min-width="100px"
        label="门店名称"
        prop="brandName"
        sortable
      />
      <el-table-column
        align="center"
        min-width="100px"
        label="统计日期"
        prop="statisDay"
        sortable
      />

      <el-table-column
        align="center"
        min-width="80px"
        label="订单笔数"
        prop="orderCnt"
      />

      <el-table-column
        align="center"
        min-width="80px"
        label="商品总额"
        prop="goodsAmount"
      />

      <el-table-column
        align="center"
        min-width="80px"
        label="优惠总额"
        prop="discountAmount"
      />

      <el-table-column
        align="center"
        min-width="80px"
        label="订单总额"
        prop="orderAmount"
      />

      <el-table-column
        align="center"
        min-width="80px"
        label="代理佣金"
        prop="settlementAmount"
      />

      <el-table-column
        align="center"
        min-width="80px"
        label="实际收入"
        prop="actualAmount"
      />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

  </div>
</template>

<style>
.itemTitle {
  font-size: small;
}

.itemNum {
  color: #ff4b41;
  font-size: x-large;
  padding: 10px;
  padding-left: 0px;
}

.filter-container {
  margin-top: 20px;
}

.el-icon-question {
  color: #ff4b41;
}

.el-range-separator {
  width: auto !important;
}
</style>

<script>
import { apply, cashierList, listBill, merchantOverview, overview } from '@/api/business/bill'
import { notIntOrDecimal } from '@/utils/validate'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import CountTo from 'vue-count-to'
import { listBrand } from '@/api/business/brand'

const typeMap = {
  // 1: "微信",
  // 2: "银行",
  3: '线下'
}
export default {
  components: {
    CountTo,
    Pagination
  },
  filters: {
    typeFilter(type) {
      return typeMap[type]
    }
  },
  data() {
    return {
      list: undefined,
      totalAmount: 0.0,
      totalCostPrice: 0.0,
      currAmount: 0.0,
      curCostPrice: 0.0,
      totalSettlementAmount: 0.0,
      curSettlementAmount: 0.0,
      withdrawableAmount: 0.0,
      orderCnt: 0,
      refundCnt: 0,
      batchList: [],
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        goodsSn: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc',
        dateRange: '',
        approveStatusArray: []
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      tableData3: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      downloadLoading: false,
      form: {
        withdrawType: '3',
        amt: ''
      },
      dialogStatus: '',
      typeMap,
      formLabelWidth: '120px',
      rules: {
        amt: [
          { required: true, message: '提现金额不能为空', trigger: 'blur' },
          { validator: notIntOrDecimal, trigger: 'blur' }
        ]
      },
      brandList: [],
      dataForm:{
        brandId : ''
      }
    }
  },
  created() {
    this.getBrandList()
  },
  methods: {
    getBrandList() {
      listBrand().then(response => {
        let data = response.data.data.items
        if (data.length > 0) {
          data.forEach(item => {
            if (item.id != 1001000) {
              this.brandList.push(item)
            }
          })
          if (this.brandList.length > 0) {
            this.listQuery.brandId = this.brandList[0].id
            this.dataForm.brandId = this.brandList[0].id
          }
          this.getList()
          this.init()
        }
      }).catch((res) => {
        this.brandList = []
        console.log(res)
      })
    },
    resetForm() {
      this.form = {
        withdrawType: '3',
        amt: ''
      }
    },
    handleApply() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    init() {
      merchantOverview(this.dataForm)
        .then((response) => {
          const overviewData = response.data.data
          this.totalAmount = overviewData.totalAmount
          this.totalCostPrice = overviewData.totalCostPrice
          this.withdrawableAmount = overviewData.withdrawableAmount
          this.currAmount = overviewData.currAmount
          this.curCostPrice = overviewData.curCostPrice
          this.orderCnt = overviewData.orderCnt
          this.refundCnt = overviewData.refundCnt
          this.totalSettlementAmount = overviewData.totalSettlementAmount
          this.curSettlementAmount = overviewData.curSettlementAmount
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getList() {
      this.listLoading = true
      cashierList(this.listQuery)
        .then((response) => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    apply() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          apply(this.form)
            .then((response) => {
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建提现申请成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = [
          '统计日期',
          '订单笔数',
          '退款笔数',
          '核销券数量',
          '商品总额',
          '优惠总额',
          '物流费',
          '订单总额',
          '总退款金额',
          '冲正金额',
          '代理佣金',
          '运营费',
          '实际收入'
        ]
        const filterVal = [
          'statisDay',
          'orderCnt',
          'refundCnt',
          'couponCnt',
          'goodsAmount',
          'discountAmount',
          'freightAmount',
          'orderAmount',
          'refundAmount',
          'refundReversalAmount',
          'settlementAmount',
          'busiAmount',
          'actualAmount'
        ]
        excel.export_json_to_excel2(
          tHeader,
          this.list,
          filterVal,
          '日销售统计账单'
        )
        this.downloadLoading = false
      })
    }
  }
}
</script>
